package org.cmroot.certmaster.client.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import org.cmroot.certmaster.client.GWTClientService;
import org.cmroot.certmaster.shared.dto.ext.ExtensionDTO;
import org.cmroot.certmaster.shared.dto.ext.Pkcs10ExtDTO;
import org.cmroot.certmaster.shared.dto.ext.X509ExtDTO;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Copyright (c) 2011 Andrey Domas <andrey.domas at gmail.com>.
 * *
 * This file is part of certmaster.
 * *
 * Certmaster is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * *
 * Certmaster is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see http://www.gnu.org/licenses
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301  USA
 */

public class OpensslText extends Composite {

    interface OpensslTextUiBinder extends UiBinder<Widget, OpensslText> {
    }

    private static OpensslTextUiBinder _opensslTextUiBinder = GWT.create(OpensslTextUiBinder.class);

    @UiField
    TextArea text;
    private ErrorLabel errorLabel;
    private final static String MARGIN = "    ";

    @UiConstructor
    public OpensslText(ErrorLabel errorLabel) {
        initWidget(_opensslTextUiBinder.createAndBindUi(this));
        this.errorLabel = errorLabel;
    }

    public void showCert(Long id) {
        getCert(id);
    }

    public void showReq(Long id) {
        getReq(id);
    }

    private void getReq(Long id) {
        GWTClientService.App.getInstance().getExtPkcs10(id, new AsyncCallback<Pkcs10ExtDTO>() {
            @Override
            public void onFailure(Throwable throwable) {
                errorLabel.showError(throwable.getMessage());
            }

            @Override
            public void onSuccess(Pkcs10ExtDTO pkcs10ExtDto) {
                printReq(pkcs10ExtDto);
            }
        });
    }

    private void getCert(Long id) {
        GWTClientService.App.getInstance().getExtX509(id, new AsyncCallback<X509ExtDTO>() {
            @Override
            public void onFailure(Throwable throwable) {
                errorLabel.showError(throwable.getMessage());
            }

            @Override
            public void onSuccess(X509ExtDTO x509ExtDTO) {
                printCert(x509ExtDTO);
            }
        });
    }

    private static String margin(int repeat_count) {
        StringBuilder result = new StringBuilder(repeat_count);
        for ( int i = 1; i <= repeat_count; i++ ) {
            result.append(MARGIN);
        }
        return result.insert(0, "\n").toString();
    }

    private static String printExtension(List<ExtensionDTO> extensions) {

        StringBuilder strb = new StringBuilder();

        for (ExtensionDTO ext : extensions) {
            strb.append(margin(3));
            strb.append(ext.getName() + ":");
            if (ext.isCritical()) { strb.append(" critical"); }
            for (String ext_value : ext.getValues()) {
                strb.append(margin(4)).append(ext_value);
            }

        }

        return strb.toString();
    }

    private void printReq(Pkcs10ExtDTO req) {
        text.setText("test");
    }

    private void printCert(X509ExtDTO cert) {

        text.setText(
                "Certificate:" +
                margin(1) + "Data:" +
                margin(2) + "Version: " + cert.getVersion() +
                margin(2) + "Serial Number: " + cert.getSerial() +
                margin(2) + "Signature Algorithm: " + cert.getSignature_alg() +
                margin(2) + "Issuer: " + cert.getIssuerDN() +
                margin(2) + "Validity" +
                margin(3) + "Not Before: " + cert.getNotBefore() +
                margin(3) + "Not After : " + cert.getNotAfter() +
                margin(2) + "Subject: " + cert.getDN() +
                margin(2) + "Subject Public Key Info:" +
                margin(3) + "Public Key Algorithm: " + cert.getPubKey_alg() +
                margin(3) + "RSA Public Key: (" + cert.getPubkey_modulus_length() + " bit)" +
                margin(4) + "Modulus (" + cert.getPubkey_modulus_length() + " bit)" +
                margin(5) + cert.getPubkey_modulus().replaceAll("((([a-f]|[0-9]){2}):){15}", "$0" + margin(5)) +
                margin(4) + "Exponent: " + cert.getPubkey_exponent() +
                margin(2) + "X509v3 extensions:" +
                printExtension(cert.getExtensions())
        );
    }
}